<template>
  <div class="case">
    <Overlay :show="showLoading" @click="show = false">
      <div class="wrapper" @click.stop>
        <Loading type="spinner" color="#1989fa" />
      </div>
    </Overlay>
    <NavBar title="创建案件" left-text="" :left-arrow="false" />
    <Form @submit="onSubmit">
      <h2 class="form-title">报案人信息（必填）</h2>
      <Field
        v-model="formData.userName"
        name="出险人"
        label="出险人"
        placeholder="出险人"
        :readonly="isUpdate"
        :rules="[{ required: true, message: '请填写出险人姓名' }]"
      />
      <Field
        v-model="formData.userMobile"
        name="手机号码"
        label="手机号码"
        placeholder="手机号码"
        :readonly="isUpdate"
        :rules="[{ required: true, message: '请填写手机号码' }]"
      />
      <Field
        v-model="formData.userIdCard"
        name="身份证号"
        label="身份证号"
        placeholder="身份证号"
        :readonly="isUpdate"
        :rules="[{ required: true, message: '请填写身份证号' }]"
      />
      <Field
        readonly
        clickable
        name="area"
        :value="responsibilityData[formData.responsibilityIds]"
        label="责任类型"
        placeholder="责任类型"
        :rules="[{ message: '请选择责任类型' }]"
        @click="showPopup('showResponsibilityIds', !isUpdate)"
      />
      <h2 class="form-title">事故信息</h2>
      <Field
        readonly
        clickable
        name="datetimePicker"
        :value="formData.accidentDate"
        label="事故时间"
        placeholder="点击选择时间"
        :rules="[{ required: true, message: '请选择事故时间' }]"
        @click="showPopup('showAccidentDatePicker', !isUpdate)"
      />
      <Field
        readonly
        clickable
        name="area"
        :value="accidentRegionCodeValue"
        label="地区选择"
        placeholder="点击选择省市区"
        :rules="[{ required: true, message: '请选择省市区' }]"
        @click="showPopup('showAccidentRegionCode', !isUpdate)"
      />
      <Field
        v-model="formData.accidentAddress"
        name="具体地址"
        label="具体地址"
        placeholder="具体地址"
        :rules="[{ required: true, message: '请选择具体地址' }]"
      />
      <Field
        v-model="formData.accidentDesc"
        name="事故描述"
        label="事故描述"
        placeholder="事故描述"
      />
      <!-- <Field
        readonly
        clickable
        name="picker"
        :value="formData.accidentTypeIdsValue"
        label="出险类型"
        placeholder="请选择出险类型"
        @click="showAccidentTypeIds = true"
      /> -->
      <Field name="checkbox" label="出险类型">
        <template #input>
          <CheckboxGroup
            v-model="formData.accidentTypeIds"
            direction="horizontal"
          >
            <Checkbox
              v-for="item in accidentTypeIdsOptions"
              :key="item.value"
              :name="item.value"
              shape="square"
            >{{ item.text }}</Checkbox>
          </CheckboxGroup>
        </template>
      </Field>
      <Field name="uploader" label="事故照片（不超过10张）">
        <template #input>
          <Uploader
            v-model="fileList"
            :max-count="10"
            :max-size="5 * 1024 * 1024"
            :after-read="afterRead"
            @delete="onDelete"
          />
        </template>
      </Field>
      <div style="margin: 16px;">
        <Button round block type="info" native-type="submit">下一页</Button>
      </div>
    </Form>
    <!-- 弹窗 -->
    <Popup v-model="showResponsibilityIds" position="bottom">
      <Picker
        title="责任类型"
        show-toolbar
        :columns="responsibilityColumns"
        @confirm="data => onPickerConfirm(data, 'responsibilityIds')"
        @cancel="showResponsibilityIds = false"
      />
    </Popup>
    <Popup v-model="showAccidentDatePicker" position="bottom">
      <DatetimePicker
        type="datetime"
        @confirm="value => onTimeConfirm(value, 'accidentDate')"
        @cancel="showAccidentDatePicker = false"
      />
    </Popup>
    <Popup v-model="showAccidentTypeIds" position="bottom">
      <Picker
        title="出险类型"
        show-toolbar
        :columns="accidentTypeIdsOptions"
        @confirm="data => onPickerConfirm(data, 'accidentTypeIds')"
        @cancel="showAccidentTypeIds = false"
      />
    </Popup>
    <Popup v-model="showAccidentRegionCode" position="bottom">
      <Area
        :area-list="areaList"
        @confirm="onAreaConfirm"
        @cancel="showAccidentRegionCode = false"
      />
    </Popup>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import {
  Button,
  NavBar,
  Form,
  Field,
  Picker,
  Popup,
  DatetimePicker,
  Area,
  Uploader,
  CheckboxGroup,
  Checkbox,
  Loading,
  Overlay
} from 'vant'
import { mapGetters } from 'vuex'
import { areaList } from '@vant/area-data'
import { upload } from '@/utils/upload'
import { debounce } from '@/utils'
import {
  userApply,
  userApplyMatching,
  updateUserApply
} from '@/api/insurance/case'

const responsibilityData = {
  1: '全责',
  2: '主责',
  3: '次责',
  4: '五五责',
  5: '无责',
  6: '摔伤'
}
const accidentTypeIdsData = {
  1: '自身受伤',
  2: '三者受伤',
  3: '三者物损'
}

export default {
  name: 'CreateCaseH5',
  components: {
    Button,
    NavBar,
    Form,
    Field,
    Picker,
    Popup,
    DatetimePicker,
    Area,
    Uploader,
    CheckboxGroup,
    Checkbox,
    Loading,
    Overlay
  },
  data: () => {
    return {
      formData: {
        accidentDate: ''
      },
      isUpdate: false,
      showLoading: false,
      areaList,
      fileList: [],
      accidentRegionCodeValue: '',
      showResponsibilityIds: false,
      showAccidentDatePicker: false,
      showAccidentTypeIds: false,
      showAccidentRegionCode: false,
      responsibilityData,
      accidentTypeIdsData,
      responsibilityColumns: Object.keys(responsibilityData).map(key => ({
        value: key,
        text: responsibilityData[key]
      })),
      accidentTypeIdsOptions: Object.keys(accidentTypeIdsData).map(key => ({
        value: key,
        text: accidentTypeIdsData[key]
      }))
    }
  },
  computed: {
    ...mapGetters(['imagesUploadApi', 'baseApi']),
    formDataNewVal() {
      return JSON.parse(JSON.stringify(this.formData))
    }
  },
  watch: {
    formDataNewVal: {
      deep: true,
      handler(newVal = {}, oldVal = {}) {
        const {
          userMobile: oldUserMobile,
          accidentDate: oldAccidentDate
        } = oldVal
        const { userMobile, accidentDate, accidentRegionCode } = newVal
        this.generateAccidentRegionCodeValue(accidentRegionCode)
        if (
          (oldUserMobile !== userMobile || oldAccidentDate !== accidentDate) &&
          userMobile &&
          accidentDate &&
          userMobile.trim() &&
          accidentDate.trim()
        ) {
          this.showLoading = true
          this.getUserApplyMatching({
            mobile: userMobile.trim(),
            time: dayjs(accidentDate.trim()).valueOf()
          })
        }
      }
    }
  },
  created() {},
  methods: {
    generateAccidentRegionCodeValue(accidentRegionCode) {
      if (accidentRegionCode && accidentRegionCode.length) {
        this.accidentRegionCodeValue = `${
          areaList.province_list[accidentRegionCode[0]]
        }/${areaList.city_list[accidentRegionCode[1]]}/${
          areaList.county_list[accidentRegionCode[2]]
        }`
      } else {
        this.accidentRegionCodeValue = ''
      }
    },
    showPopup(type, can_change) {
      if (can_change) {
        this[type] = true
      }
    },
    onPickerConfirm(data, key = '') {
      const isSimple = typeof data === 'string' || typeof data === 'number'
      this.formData[key] = isSimple ? data : data.value
      this.formData[`${key}Value`] = isSimple ? data : data.text
      const _key = `show${key.slice(0, 1).toUpperCase() + key.slice(1)}`
      this[_key] = false
    },
    onTimeConfirm(data, key) {
      this.formData[key] = dayjs(data).format('YYYY-MM-DD HH:mm:ss')
      this.showAccidentDatePicker = false
    },
    onAreaConfirm(resp) {
      const [province, city, county] = resp
      this.formData['accidentRegionCode'] = [].concat([
        province.code,
        city.code,
        county.code
      ])
      this.generateAccidentRegionCodeValue(this.formData['accidentRegionCode'])
      this.showAccidentRegionCode = false
    },
    /** */
    getUserApplyMatching: debounce(function(payload) {
      userApplyMatching(payload)
        .then(res => {
          console.log('根据手机号码和时间戳匹配一个案件', res)
          this.isUpdate = !!res
          if (res) {
            this.formData = {
              ...res,
              accidentTypeIds: res.accidentTypeIds
                ? res.accidentTypeIds.map(item => '' + item)
                : []
              // fileList: res.fileList
              //   ? res.fileList.map(url => this.baseApi + '/file/图片/' + url)
              //   : []
            }
            this.fileList = res.fileList
              ? res.fileList.map(name => ({
                name,
                url: this.baseApi + '/file/图片/' + name
              }))
              : []
          }
        })
        .finally(() => {
          this.showLoading = false
        })
    }, 800),
    /**
     * 案件申请
     */
    onSubmit() {
      const submitFn = this.isUpdate ? updateUserApply : userApply
      submitFn({
        ...this.formData,
        fileList: (this.formData.fileList || []).filter(url => !!url)
      }).then(res => {
        if (res) {
          this.$router.push({ path: '/h5/case/replenish', query: { id: res }})
        }
      })
    },
    afterRead({ file }) {
      file.status = 'uploading'
      file.message = '上传中...'
      upload(this.imagesUploadApi, file)
        .then(res => {
          const data = res.data
          const url = this.baseApi + '/file/' + data.type + '/' + data.realName
          console.log(url)
          file.status = 'done'
          file.message = '上传成功'
          this.formData.fileList = this.formData.fileList || []
          this.formData.fileList.push(data.realName)
        })
        .catch(() => {
          file.status = 'failed'
          file.message = '上传失败'
          this.formData.fileList = this.formData.fileList || []
          this.formData.fileList.push('')
        })
    },
    onDelete(file, detail) {
      const { index } = detail
      if (index >= 0) {
        this.formData.fileList.splice(index, 1)
        // this.fileList.splice(index, 1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.case {
  background-color: #fafafa;
  & >>> .van-checkbox {
    margin-bottom: 8px;
  }
  & >>> .van-overlay {
    background-color: rgba(0, 0, 0, 0);
  }
}
.form-title {
  margin: 0;
  padding: 16px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
  line-height: 16px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
